﻿using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System.Web.Mvc;
using System.Linq;
using System.Drawing;
using Pay.Core;
using System.IO;
using Flurl.Http;
using System.Web;

namespace Pay.H5.Controllers
{
	[AppAuthorize("Member")]
    public class ProductController : GeneralController {
        public ProductController() { }
        private  IProductService _productService ;
        private ICategoryService _categoryService;
        private IMerchantService _merchantService;
        private ICollectService _collectService;
		private IOrderService _iOrderService;
        public ProductController(IProductService productService, ICollectService collectService, 
		                         ICategoryService categoryService,IMerchantService merchantService,
		                         IOrderService iOrderService)
        {
          _productService = productService;
            _categoryService = categoryService;
            _merchantService = merchantService;
            _collectService = collectService;
			_iOrderService = iOrderService;
        }
		#region 收藏产品
		public JsonResult Collect(long ProductId) {
			var model = _collectService.GetCollect(UserId, ProductId);
			if (model != null) {
				var result = _collectService.DelCollect(UserId, ProductId);
				if (result > 0) {
					api_result.result_msg = "取消成功";
					api_result.result_code = 1000;
				}
			} else {
				var result = _collectService.Add(UserId, ProductId);
				if (result > 0) {
					api_result.result_msg = "收藏成功";
					api_result.result_code = 1000;
				}
			}
			return Json(api_result, JsonRequestBehavior.AllowGet);
		}
        #endregion
		/// <summary>
		/// 产品类型
		/// </summary>
		/// <returns>The category.</returns>
		/// <param name="CategryId">Categry identifier.</param>
		[AllowAnonymous]
		public ActionResult ProductCategory(long? CategryId) {
			var merchent = _merchantService.Get(Models.RequestMethodh5.MerchantNO);
			var list = _categoryService.GetAll(merchent.id);
            var html = "";
			if (list != null && list.Count > 0) {
				var query = new GoodsQuery();
				query.merchant_id = merchent.id;
				query.category_id = CategryId.HasValue ? CategryId.Value : list.FirstOrDefault().id;
				query.size = 100;
				var productlist = _productService.Get(query);
				if (productlist.rows != null && productlist.rows.Count > 0) {
					foreach (var product in productlist.rows)
						if (product.name.Length > 10) {
							var image = site.img_url + product.first_image;
							html = html + " <li> <a href = '/Product/ProductDetail/" + product.id + "'> <img src = '" + image + "' class='class_pic' />  <p class='class_title'>" + product.name.Substring(0, 10) + "</p> </a>  </li>";
						} else {
							html = html + " <li> <a href = '/Product/ProductDetail/" + product.id + "'> <img src =  '" + site.img_url + product.first_image + "' class='class_pic' />  <p class='class_title'>" + product.name + "</p> </a>  </li>";
						}
				}
			}
            ViewData["html"] = html;
            ViewData["list"] = list;
			ViewData["merchantid"] = merchent.id;
			ViewData["url"] = site.img_url;
            return View();
        }
		/// <summary>
		/// 商品列表
		/// </summary>
		/// <returns>The list.</returns>
		/// <param name="type">Type.</param>
		/// <param name="MerchantNo">Merchant no.</param>
		/// <param name="sort">Sort.</param>
		[AllowAnonymous]
        public ActionResult ProductList(string type,string MerchantNo,int sort=0)
        {
            GoodsQuery query = new GoodsQuery();
            var category = _categoryService.GetCategoryByName(type);
            if (category != null)
            {
                query.category_id = category.id;

            }
            var model = _merchantService.Get(MerchantNo);
            if (model != null)
            {
                if (model.is_supplier == true)//供应商
                {
                    query.merchant_id = model.id;

                }
                else if (model.usertype == UserType.oem)//oem
                {
                    MerchantQuery merchantquery = new MerchantQuery();
                    merchantquery.parent_id = model.id;
                    merchantquery.auth_status = AuthStatusEnum.Auth;
                    merchantquery.disabled = false;
                    merchantquery.usertype = UserType.oem;
                    var merchantlist = _merchantService.GetMerchant(merchantquery);
                    if (merchantlist != null && merchantlist.rows.Count > 0)
                    {
                        query.merchant_id = merchantlist.rows[0].id;
                       
                    }
                }
                else
                {//分销商
                    query.merchant_id = model.id;
                   
                }
            }
            query.sort = sort;
            query.sale_status = 0;
            query.sell_out = false;
            query.audit_status = 1;
            var list = _productService.Get(query);
            ViewData["list"] = list;
			ViewData["url"] = site.img_url;
            return View();
        }
        /// <summary>
        /// 商品详情
        /// </summary>
        /// <returns>The detail.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="merchant_no">Merchant no.</param>
		[AllowAnonymous]
		public ActionResult ProductDetail(int id,string merchant_no)
        {
            var model = _productService.Get(id);
            #region 获取相关产品
            GoodsQuery query = new GoodsQuery();
            query.sale_status = 0;
            query.sell_out = false;
            query.audit_status = 1;
            query.size = 4;
            query.merchant_id = model.merchant_id;
            var list = _productService.Get(query);//获取相关产品
            #endregion
            ViewData["url"] = site.img_url;
            ViewData["list"] = list;
            ViewData["product"] = model;
			if (UserId > 0) {
				var merchant = _merchantService.Get(UserId);
				string share_url = "http://" + Request.Url.Authority + "/product/productdetail?id=" + id + "&merchant_no=" + merchant.merchant_no;
				ViewData["merchant_no"] = merchant.merchant_no;
				ViewData["share_url"] = share_url;
				_iOrderService.ClearOrderList(UserId);
			} else {
				Response.Cookies.Remove("cache_no");
				byte[] cacheBytes = System.Text.Encoding.Default.GetBytes(DtoHelper.GenerateOrderNumber());
				Response.Cookies.Add(new HttpCookie("cache_no", System.Convert.ToBase64String(cacheBytes)));
			}
			
			//分销用户编号
			if (!string.IsNullOrEmpty(merchant_no)) {
                //写cookie 分销商户号、缓存key订单号
                Response.Cookies.Remove("share_no");
                byte[] merBytes = System.Text.Encoding.Default.GetBytes(merchant_no);
                Response.Cookies.Add(new HttpCookie("share_no", System.Convert.ToBase64String(merBytes)));
				return View("DisProductDetail");
			}

            return View();
        }

		public JsonResult GetData(long Id) {
			var oem = _merchantService.Get(Models.RequestMethodh5.MerchantNO);
			var query = new GoodsQuery {
				category_id = Id,
				merchant_id = oem.id,
				size = 100
			};
			var list = _productService.Get(query);
			return Json(new { code = 1000, msg = "数据获取成功", data = list }, JsonRequestBehavior.AllowGet);
		}
		/// <summary>
		/// 图片合成
		/// </summary>
		/// <returns>The merge.</returns>
		/// <param name="product_id">Product identifier.</param>
		/// <param name="merchant_no">Merchant no.</param>
		[HttpGet]
		public FileResult ImageMerge(long product_id,string merchant_no) {
			var product = _productService.Get(product_id);
			var merchant = _merchantService.Get(UserId);
			string image_url = site.img_url + product.first_image;
            string image_100 = string.Format("http://{0}/Content/images/100.png", Request.Url.Authority);
            string share_url = string.Format("http://{0}/product/productdetail?id={1}&merchant_no={2}", Request.Url.Authority, product_id, merchant_no);
			Bitmap canves = new Bitmap(311, 552);//新建大小为311×552大小的画布
            Bitmap img100 = DownLoadFile(image_100);
            Bitmap productImage = DownLoadFile(image_url);
			Graphics graphics = Graphics.FromImage(canves);
			graphics.FillRectangle(Brushes.White, new Rectangle(0, 0, 311, 552));
			//底部背景颜色
			graphics.FillRectangle(new SolidBrush(Color.FromArgb(243, 243, 243)), new Rectangle(0, 402, 311, 300));
			Font font = new Font("微软雅黑", 10, FontStyle.Regular);
			Brush brush = new SolidBrush(Color.Gray);
			//价格
			Brush price = new SolidBrush(Color.FromArgb(208, 2, 27));
			graphics.DrawString(product.price.ToString("c"), new Font("微软雅黑", 13, FontStyle.Bold), price, 30, 330);

			Brush mPrice = new SolidBrush(Color.FromArgb(102, 102, 102));
			graphics.DrawString(product.market_price.ToString("c"), new Font("微软雅黑", 10, FontStyle.Strikeout), mPrice, 110, 333);
			//标题
			Brush title = new SolidBrush(Color.FromArgb(71, 71, 71));
			graphics.DrawString(product.name, new Font("微软雅黑", 10, FontStyle.Bold), title, 30, 360);
			//商品描述

			//RectangleF rec = new RectangleF(0, 0, 70, 70);
			//DrawStringEx(text, graphics, new PointF { X = 30, Y = 260 }, font, brush, 2);
			//Brush des = new SolidBrush(Color.FromArgb(102, 102, 102));
			//graphics.DrawString(product.short_description, new Font("微软雅黑", 9, FontStyle.Regular), des,
			//												new RectangleF(30, 260, 250, 100));

			graphics.DrawString("扫码立即下单购买", font, brush, 182, 524);
			//第一张图片
			graphics.DrawImage(productImage, 0, 0, 311, 311);
			//100包邮
			graphics.DrawImage(img100, 40, 430, 110, 110);
			//二维码
			Bitmap codeUrl = QRCodeHelper.CreateImgCode(share_url, 20);
			graphics.DrawImage(codeUrl, 185, 422, 100, 100);

			MemoryStream ms = new MemoryStream();
			canves.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
			graphics.Dispose();
			return File(ms.ToArray(),"image/jpeg");
		}
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private Bitmap DownLoadFile(string url) {
            byte[] bytes = url.GetBytesAsync().Result;
            MemoryStream ms = new MemoryStream(bytes);
            return new Bitmap(ms);
        }
    }
}